package com.cunzhang.server.service.impl;

import com.cunzhang.common.constants.MessageConstant;
import com.cunzhang.common.result.PageResult;
import com.cunzhang.pojo.dto.CategoryDTO;
import com.cunzhang.pojo.dto.CategoryPageQueryDTO;
import com.cunzhang.pojo.entity.Category;
import com.cunzhang.server.mapper.CategoryMapper;
import com.cunzhang.server.service.CategoryService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    /**
     * 分页查询分类
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryCategory(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize());
        Page<Category> page = categoryMapper.pageQueryCategory(categoryPageQueryDTO.getName(), categoryPageQueryDTO.getType());

        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(page.getResult());
        return pageResult;
    }

    /**
     * 根据类型查询分类
     * @param type
     * @return
     */
    @Override
    public List<Category> queryCategoryByType(Integer type) {
        Category category = new Category();
        category.setType(type);
        return categoryMapper.selectCategory(category);
    }

    /**
     * 修改类别信息
     * @param categoryDTO
     */
    @Override
    public void editCategory(CategoryDTO categoryDTO) {
        Category queryCondition = new Category();
//        BeanUtils.copyProperties(categoryDTO, queryCondition);
        queryCondition.setId(categoryDTO.getId());
        List<Category> categoryList = categoryMapper.selectCategory(queryCondition);

        //无查询结果或查询结构不唯一
        if(categoryList == null || categoryList.size() != 1){
            throw new RuntimeException(MessageConstant.UNKNOWN_ERROR);
        }

        Category category = categoryList.get(0);
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.updateCategory(category);
    }

    /**
     * 新增分类
     * @param categoryDTO
     */
    @Override
    public void addCategory(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        categoryMapper.insertCategory(category);
    }


}
